package com.siro.auth.utils.http;

import cn.hutool.json.JSONUtil;
import net.sf.json.util.JSONUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * http 调用第三方请求
 *
 * @author starsea
 * @date 2022-11-30 09:26
 */
public class HttpChl {

    private static final Logger logger = LoggerFactory.getLogger(HttpChl.class);

    private static CloseableHttpClient httpClient = null;

    /**
     * 调用请求
     *
     * @param url          请求地址
     * @param method       请求参数
     * @param data         请求数据
     * @param headerConfig 请求头
     * @return
     */
    public static String httpReq(String url, String method, Object data, Map<String, String> headerConfig) {
        String result = "";
        switch (method) {
            case "POST":
                result = doPost(url, data, headerConfig);
                break;
            case "GET":
                result = doGet(url, data, headerConfig);
                break;
            default:
                return "暂不支持" + method + "请求方式";
        }
        return result;
    }

    /**
     * http get请求
     *
     * @param url
     * @param data
     * @param headerConfig
     * @return
     */
    private static String doGet(String url, Object data, Map<String, String> headerConfig) {
        String result = "";
        httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        if (null != headerConfig && headerConfig.size() > 0) {
            for (Map.Entry<String, String> kv : headerConfig.entrySet()) {
                httpGet.addHeader(kv.getKey(), kv.getValue());
            }
        }
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
            } else {
                logger.debug("GET请求外部系统：请求路径：{}，请求参数：{}，返回结果：{}", url, JSONUtils.valueToString(data), String.format("%s - http recv:%s", HttpChl.class.getSimpleName(), result));
            }
        } catch (Exception e) {
            logger.error("GET请求外部系统发生错误，请求路径：{}，请求参数：{}", url, JSONUtils.valueToString(data));
        }
        return result;
    }

    /**
     * http post请求
     *
     * @param url
     * @param data
     * @param headerConfig
     * @return
     */
    private static String doPost(String url, Object data, Map<String, String> headerConfig) {
        String result = "";
        httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(JSONUtil.toJsonStr(data), "UTF-8"));

        if (null != headerConfig && headerConfig.size() > 0) {
            for (Map.Entry<String, String> kv : headerConfig.entrySet()) {
                httpPost.addHeader(kv.getKey(), kv.getValue());
            }
        }
        try {
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
            } else {
                logger.debug("POST请求外部系统：请求路径：{}，请求参数：{}，返回结果：{}", url, JSONUtils.valueToString(data), String.format("%s - http recv:%s", HttpChl.class.getSimpleName(), result));
            }
        } catch (Exception e) {
            logger.error("POST请求外部系统发生错误，请求路径：{}，请求参数：{}", url, JSONUtils.valueToString(data));
        }
        return result;
    }
}
